﻿using Microsoft.Extensions.Hosting;
using RabbitMQ.Client;
using Solution.Application.Dtos;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace Solution.Application.Workers
{
    public class RabbitMQClientPublisher : BackgroundService
    {
        private readonly ConnectionFactory _connectionFactory;

        public RabbitMQClientPublisher()
        {
            _connectionFactory = new ConnectionFactory()
            {
                UserName = "dev",
                Password = "QfV9kQzVNo7a",
                HostName = "192.168.56.102",
                VirtualHost = "/dev"
            };
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            CreateOrder();
            await Task.CompletedTask;
        }

        private void CreateOrder()
        {
            var request = new EventInput<CreateOrderInput>()
            {
                Data = new CreateOrderInput()
                {
                    UserId = 0,
                    CreateOrderTime = DateTime.UtcNow,
                }
            };

            Console.WriteLine("start create order by RabbitMQClientPublishWorker");
            for (int i = 0; i < 10; i++)
            {
                request.Data.ProductName = Guid.NewGuid().ToString();
                //PublishDelaydedMessageByPlugs("RabbitMQ.Client.Delayed.CreateOrder", "RabbitMQ.Client.Delayed.CreateOrder.Queue", request);
            }
        }

        private void PublishDelaydedMessageByPlugs<T>(string rountingKey, string queueName, T message, int delayedSeconds = 5)
        {
            var exchangeName = "plug.delay.exchange";
            using (var connection = _connectionFactory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    var exchangeArgs = new Dictionary<string, object>()
                    {
                        {"x-delayed-type","direct" }
                    };

                    //指定x-delayed-message 类型的交换机，并且添加x-delayed-type属性
                    channel.ExchangeDeclare(exchangeName, "x-delayed-message", true, false, exchangeArgs);
                    channel.QueueDeclare(queueName, true, false, false, null);
                    channel.QueueBind(queueName, exchangeName, rountingKey);

                    var properties = channel.CreateBasicProperties();
                    var headers = new Dictionary<string, object>()
                    {
                        {"x-delay",delayedSeconds*1000 }
                    };
                    properties.Persistent = true;
                    properties.Headers = headers;
                    var context = JsonSerializer.Serialize(message);
                    var body = Encoding.UTF8.GetBytes(context);
                    channel.BasicPublish(exchangeName, rountingKey, properties, body);
                }
            }
        }
    }
}